package com.liang.service.impl;


import cn.hutool.core.lang.hash.Hash;
import com.baomidou.mybatisplus.annotation.TableField;
import com.liang.mapper.ArmyxDAO;
import com.liang.mapper.UserzDAO;
import com.liang.mapper.UserzarmyxuDAO;
import com.liang.pojo.Reportforms;

import java.util.*;
import java.util.stream.Collectors;

import com.liang.mapper.ReportformsDAO;
import javax.annotation.Resource;

import com.liang.pojo.dto.ReportformsDto;
import com.liang.utils.DateUtils;
import javafx.beans.binding.ObjectExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.liang.service.ReportformsService;
import org.springframework.transaction.annotation.Transactional;

/**
 *@作者:lsk
 *Service实现类
 *@Date:2023/10/26
*/
@Service
public class ReportformsServiceImpl  implements ReportformsService{


	@Resource
	private ReportformsDAO reportformsdao;

	@Resource
	private ArmyxDAO armyxDAO;

	@Resource
	private UserzarmyxuDAO userzarmyxuDAO;

	@Value("reportformsAplay")
	private String reportformsAplayTitle;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Resource
	 private UserzDAO userzDAO;

	@Value("userReportforms")
	private String userReportformsTitle;


	/**
	根据Reportforms_id查询
	*/
	public Object selectByReportforms_id(Long reportforms_id){
		return reportformsdao.selectByReportforms_id(reportforms_id);
	}


	/**
	根据Reportforms_id更新
	*/
	public Integer updateByReportforms_id(Reportforms demo){
		return reportformsdao.updateByReportforms_id( demo);
	}



	/**
	根据Reportforms_id删除
	*/
	public Integer deleteByReportforms_id(Long reportforms_id){
		return reportformsdao.deleteByReportforms_id(reportforms_id);
	}





	/**
	 insert:(插入)
	*/
	public Object insert(Reportforms demo){
		reportformsdao.insertlsk(demo);
		return demo;
	}



	/**
	 insertOrUpdate(插入或更新(根据主键或唯一索引更新，主键和唯一索引不会改变))
	*/
	public Integer insertOrUpdate(Reportforms demo){
		return reportformsdao.insertOrUpdatelsk(demo);
	}



	/**
	 insertBath:(批量插入)
	*/
	public Integer insertBatch(List<Reportforms> list){
		return reportformsdao.insertBatchlsk(list);
	}



	/**
	 insertOrUpdateBatch:(批量插入或更新)
	*/
	public Integer insertOrUpdateBatch(List<Reportforms> list){
		return reportformsdao.insertOrUpdateBatchlsk(list);
	}



	/**
	 selectList:(根据参数查询集合)
	*/
	public List<Reportforms> selectList(Map<String,Object> param){
		if(param.get("pageNum") != null){
			int start = Integer.parseInt(param.get("pageSize").toString()) * (Integer.parseInt(param.get("pageNum").toString()) - 1);
			param.put("pageNum",start);
		}
		return reportformsdao.selectListlsk(param);
	}



	/**
	 selectCount:(根据集合查询数量)
	*/
	public Long selectCount(Map<String,Object> param){
		return reportformsdao.selectCountlsk(param);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean addReportForms(Reportforms reportforms) {

		//设置reportforms的默认值
		String todayDateTime = DateUtils.getTodayDateTime();
		reportforms.setOpinion(0);
		reportforms.setPulish_time(todayDateTime);
		reportforms.setCreate_time(todayDateTime);
		reportforms.setUpdate_time(todayDateTime);

		//存储reportforms到数据库中.
		Integer bit = reportformsdao.insertlsk(reportforms);

		//获取发布人员id
		Long pulish_id = reportforms.getPulish_id();
		//获取所在部队的army_id
		Long armyFatherId = armyxDAO.getArmyFatherId(pulish_id);
		if(bit>0){
			//将这个信息存储到他的上级redis中等待审批
			redisTemplate.opsForSet().add(reportformsAplayTitle+armyFatherId,reportforms.getReportforms_id().toString());
		}

		return  true;
	}

	/**
	 * 获取单位所有的申请通知历史
	 * @param reportformsDto
	 * @return
	 */
	@Override
	public Map GetReportFormsHistory(ReportformsDto reportformsDto) {
		HashMap<String, Object> map = new HashMap<>();

		//获取当前用户的userid
		Long user_id = reportformsDto.getUser_id();

		//获取当前用户的armyId;
		Long armyId = userzarmyxuDAO.selectArmyIdbyUserId(user_id);
		//获取属于这个armyId的所有人
		ArrayList<Long> longs = new ArrayList<>();
		longs.add(armyId);
		List userIds = userzarmyxuDAO.getUserIds(longs);

		List<ReportformsDto> list = reportformsdao.GetReportFormsHistory(reportformsDto,userIds);
		if(list.size() == 0){
			map.put("list",null);
			map.put("total",0);
		}else{
			map.put("list",list);
			map.put("total",list.size());
		}
		return  map;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map superiorAplyReportForms(ReportformsDto reportformsDto) {

		//返回值对象
		HashMap<String, Object> map = new HashMap<>();

		//获取当前用户的user_id
		Long user_id= reportformsDto.getUser_id();

		//获取当前用户的armyId;
		Long armyId = userzarmyxuDAO.selectArmyIdbyUserId(user_id);

		//从redis中获取当前army应该审批的reportformsId;
		Set<String> members = redisTemplate.opsForSet().members(reportformsAplayTitle + armyId);

		if(members.size() ==0){
			map.put("list",null);
			map.put("total",0);
		}else{
			//将set中的string转化为list
			List<Long> collect = members.stream().map(item -> {
						return Long.parseLong(item);
					}
			).collect(Collectors.toList());

			//从数据库中条件查询
		List<ReportformsDto> list =	reportformsdao.superiorAplyReportForms(collect,reportformsDto);

		//构建map
			map.put("list",list);
			map.put("total",list.size());
		}
		return map;
	}

	/**
	 * 设置上级对用户的审批操作，设置approve_id，approve_time，opinion，同时从redis中删除这个记录
	 * @param reportformsDto
	 * @return
	 */
	@Override
	public Boolean superiorApprovalReportForms(ReportformsDto reportformsDto) {

		Reportforms reportforms = new Reportforms();
		reportforms.setReportforms_id(reportformsDto.getReportforms_id());
		reportforms.setApprove_id(reportformsDto.getUser_id());
		reportforms.setOpinion(reportformsDto.getOpinion());
		reportforms.setApprove_time(DateUtils.getTodayDateTime());
		Integer integer = reportformsdao.updateByReportforms_id(reportforms);

		if(integer >0){
			//从redis中移除这个消息
			//获取当前用户的armyId

			Long user_id = reportformsDto.getUser_id();
			Long armyId = userzarmyxuDAO.selectArmyIdbyUserId(user_id);
			Long reportforms_id = reportformsDto.getReportforms_id();


			//获取armyFatherId为armyId的所有armyId
			List<Long> ArmyIds = armyxDAO.getArmyIds(armyId);
			//判断这个部队是否存在下属管理的部队
			if(ArmyIds.size() == 0){
				System.out.println(reportforms_id.toString()+"qeqeqweqeqeqwe");
				redisTemplate.opsForSet().remove(reportformsAplayTitle+armyId,reportforms_id.toString());
				return true;
			}

			//获取用户列表在上面的armyids中
			List<Long> userids = userzarmyxuDAO.getUserIds(ArmyIds);

			if(userids.size()!=0){
				for (Long userid : userids) {
					redisTemplate.opsForSet().add(userReportformsTitle+userid,reportformsDto.getReportforms_id().toString());
				}
			}
			redisTemplate.opsForSet().remove(reportformsAplayTitle+armyId,reportforms_id.toString());
			return true;
		}

		return false;

	}

	/**
	 * 获取本用户接收到的报表
	 * @param reportformsDto
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map getReportForms(ReportformsDto reportformsDto) {

		HashMap<String, Object> map = new HashMap<>();
		//获取当前用户的user_id
		Long user_id = reportformsDto.getUser_id();

		//从redis中取得报表idset

		Set<String> ids = redisTemplate.opsForSet().members(userReportformsTitle + user_id);

		if(ids.size() ==0){
			map.put("list",null);
			map.put("total",0);
		}else{
			//转化string为long
			List<Long> collect = ids.stream().map(id -> {
				return Long.parseLong(id);
			}).collect(Collectors.toList());
		 List<ReportformsDto> 	list =	reportformsdao.getReportForms(collect,reportformsDto);
		 map.put("list",list);
		 map.put("total",list.size());
		}
		return map;
	}

	/**
	 * 获取所有的报表用于师和军查看
	 * @param reportformsDto
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map getAllReportForms(ReportformsDto reportformsDto) {

		//获取所有的用户id
		List allUser = armyxDAO.getAllUser();
		List<ReportformsDto> list = reportformsdao.getAllReportForms(allUser,reportformsDto);

		HashMap<String, Object> map = new HashMap<>();

		if(list.size() ==0){
			map.put("list",null);
			map.put("total",0);
		}else{
			map.put("list",list);
			map.put("total",list.size());
		}
		return map;
	}


}